package com.xiu.weixin.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiu.weixin.service.wx.CheckTokenService;
import com.xiu.weixin.service.wx.WxService;
import com.xiu.weixin.util.XmlUtil;

@RequestMapping("wx")
@Controller
public class WxController {
	private static final Logger logger = LoggerFactory.getLogger(WxController.class);

	@Autowired
	private CheckTokenService checkTokenService;
	@Autowired
	private WxService wxService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	@ResponseBody
	public String doGet(HttpServletRequest request) {
		logger.info("LocalAddr:" + request.getLocalAddr());
		logger.info("RemoteHost:" + request.getRemoteHost());
		logger.info("RemoteAddr:" + request.getRemoteAddr());
		logger.info("RemotePort:" + request.getRemotePort());
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		logger.info("signature:" + signature);
		logger.info("timestamp:" + timestamp);
		logger.info("nonce:" + nonce);
		logger.info("echostr:" + echostr);
		if (checkTokenService.check(signature, timestamp, nonce)) {
			logger.info("接入成功");
			return echostr;
		}
		logger.info("接入失败");
		return null;

	}

	@RequestMapping(name = "", method = RequestMethod.POST)
	@ResponseBody
	public String doPost(HttpServletRequest request) throws Exception {
		// 解析请求xml为map
		Map<String, String> reqMap = XmlUtil.parseRequrst(request.getInputStream());
		logger.info("reqMap:\n" + reqMap);
		// 处理消息，并返回响应xml
		String rspXml = wxService.doService(reqMap);
		logger.info("rspXml:\n" + rspXml);
		return rspXml;
	}
}
